package alvarodelrosal.chat.server.modelo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ChatConversation {

    private int id;
    private String name;
    private Set<ChatUser> historicUsers = new HashSet();
    private Set<ChatConnection> connections = new HashSet();
    private List<ChatMessage> messages = new ArrayList();
    private final Object lock = new Object();

    public ChatConversation(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void addConnection(ChatConnection newConnection) {
        if (connections.size() > 0) {
            sendToAllConnections("AddToChat<:@:>" + id + "<:@:>" + newConnection.whoAmI().getUserId());
        }
        connections.add(newConnection);
        historicUsers.add(newConnection.whoAmI());
    }

    private void sendToAllConnections(String text) {
        synchronized (lock) {
            for (ChatConnection connection : connections) {
                connection.send(text);
            }
        }
    }

    public void addMessage(ChatMessage message) {
        sendMessage(message);
        synchronized (lock) {
            messages.add(message);
        }
    }

    private void sendMessage(ChatMessage message) {
        sendToAllConnections("Chat<:@:>" + id + "<:@:>" + message.getUser().getUserId() + "<:@:>" + message.getText());
    }

    public boolean hasUser(int userId) {
        synchronized (lock) {
            for (ChatConnection connection : connections) {
                if (connection.whoAmI().getUserId() == userId) {
                    return true;
                }
            }
            return false;
        }
    }

    public void removeConnection(ChatConnection connection) {
        synchronized (lock) {
            connections.remove(connection);
        }
        sendToAllConnections("ByeChat<:@:>" + id + "<:@:>" + connection.whoAmI().getUserId());
    }

    public Set<ChatConnection> getConnections() {
        synchronized (lock) {
            return connections;
        }
    }

    public Set<ChatUser> getHistoricUsers() {
        return historicUsers;
    }

    public List<ChatMessage> getMessages() {
        synchronized (lock) {
            return messages;
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final ChatConversation other = (ChatConversation) obj;
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 79 * hash + this.id;
        hash = 79 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 79 * hash + (this.messages != null ? this.messages.hashCode() : 0);
        return hash;
    }
}
